package com.fg.common.response;

import com.fg.common.enums.ResponseEnum;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Map;

/**
 * 统一返回结果类
 * @author lv
 * @version 1.0.0
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
@ApiModel("全局统一返回对象")
@NoArgsConstructor
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    @ApiModelProperty(value = "状态码",example = "00000",required = true)
    private String code;

    /**
     * 状态描述
     */
    @ApiModelProperty(value = "状态描述",example = "success",required = true)
    private String message;

    /**
     * 返回内容
     */
    @ApiModelProperty(value = "响应内容",required = true)
    private T data;

    /**
     * 获取返回内容
     * @param response 响应码枚举对象
     * @param data 响应数据
     * @param <T> 响应数据类型
     * @return R
     */
    public static <T> R<T> build(Response response, T data){
        return build(response.getCode(), response.getMessage(), data);
    }

    public static <T> R<T> build(String code, String message, T data){
        return new R<T>(code, message, data);
    }

    public static <T> R<T> build(String code, String message){
        return build(code, message, null);
    }

    public static R<Object> build(Response response){
        return build(response, null);
    }

    /**
     * 获取R
     * @param isSuccess 是否成功
     * @return R
     */
    public static R<Object> build(boolean isSuccess){
        return isSuccess ? R.success() : R.error();
    }

    /**
     * 成功
     * @return R
     */
    public static <T> R<T> success(){
        return success(null);
    }


    /**
     * 成功
     * @param data 内容
     * @return R
     */
    public static <T> R<T> success(T data){
        return build(ResponseEnum.SUCCESS, data);
    }

    /**
     * c错误
     * @return R
     */
    public static  R<Object> error(){
        return build(ResponseEnum.ERROR, null);
    }

    /**
     * 错误
     * @param message 描述信息
     * @return R
     */
    public static R<Object> error(String message){
        return error().message(message);
    }

    /**
     * 使用map包装数据
     * @param key Map--->key
     * @param value Map--->value
     * @return R
     */
    public static R<Map<String,Object>> success(String key,Object value){
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(1);
        map.put(key,value);
        return R.success(map);
    }

    public R<T> data(T data){
        this.setData(data);
        return this;
    }

    public R<T> message(String message){
        this.setMessage(message);
        return this;
    }

    public R<T> code(String code){
        this.setCode(code);
        return this;
    }
}
